var httpsUrl = getApp().globalData.httpsUrl;
var globalData = getApp().globalData;
var commonUtil = require("../../../utils/commonUtil.js")
Page({
  data: {
    imgUrl: globalData.imgUrl,
    info:new Object(),
    types:[],//商家类型
    typeFlag:0,//1是展示
    areaFlag:0,//区域
    address:[],
    addressDj:0,//区域当前级别
    orderNo:"",
    //areaAreaid地区id  longitude经度 latitude 纬度 logo 商家logo license营业执照 img1
  },
  loadData:function(){
    let that = this;
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded"},
      url: httpsUrl + "/business/getMyEnterApply",
      dataType: "json",
      method: "POST",
      // data: frm,
      success: function (res) {
        commonUtil.hideLoading();
        res = res.data;
        console.log("返回：" + JSON.stringify(res));
        if (res.result == 0) {
          that.setData({info:res.data});
        } else {
          //commonUtil.showModal(res.msg);
        }
      }
    })
    this.types();
  },
  save:function(e){
    let that = this;
    var frm = e.detail.value;//form内容
    if (frm.password != frm.password2){
      commonUtil.showModal("两次输入密码不同，请重新输入");
      return;
    }
    //{"businessTypeName":"美食","businessType":"2","areaName":" 河南 郑州市 登封市","areaAreaid":"416","longitude":"113.887171","latitude":"22.554628","name":"商户名称1","address":"广东省深圳市宝安区地铁1号线(罗宝线),地铁5号线(环中线)等2条线路","contact":"班班","phone":"13246624632","consume":"90","hasPack":"0","hasWifi":"0","hasBox":"0","shopHourStart":"8：00","shopHourEnd":"24：00","userName":"132","password":"111","password2":"111"}
    let info = this.data.info;
    frm.license = info.license;
    frm.logo = info.logo;
    frm.img1 = info.img1;
    frm.img2 = info.img2;
    frm.img3 = info.img3;
    console.log("frm：" + JSON.stringify(frm));
    commonUtil.showLoading("请稍等...");
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, },
      url: httpsUrl + "/business/enterApply",
      dataType: "json",
      method: "POST",
      data: frm,
      success: function (res) {
        commonUtil.hideLoading();
        res = res.data;
        console.log("返回：" + JSON.stringify(res));
        if (res.result == 0) {
          // wx.showToast({title: '申请已提交！',})
          let orderNo = res.data;
          if (orderNo != '' && orderNo != null && orderNo.length>0){
            console.log("有订单号");
            that.setData({ orderNo: orderNo})
            that.goPay();
          }else{
            wx.showModal({
            title: '提示',
            content: '申请提交成功，请等待审核结果通知哦！',
            success: function (res) {
              if (res.confirm) {
                wx.navigateBack({ delta: 1 })
              } else if (res.cancel) { 
                wx.navigateBack({ delta: 1 })
              }
            }
          })
          }
        } else {
          commonUtil.showModal(res.msg);
        }
      }
    })
  },
  address:function(id){
    let that = this;
    var params = new Object();
    if(id != ''){
      params.parentId = id;//父级区域ID
    }
    console.log("param：" + JSON.stringify(params));
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/business/getAreaList",
      dataType: "json",
      method: "GET",
      data: params,
      success: function (res) {
        console.log("区域：" + JSON.stringify(res));
        res = res.data;
        if (res.result == 0) {
          let rows = res.data;
          that.setData({ address: rows })
        }
      }
    })
  },
  areaFlag: function () {
    this.setData({ areaFlag: 1 })
    this.address("");
    this.setData({ addressStr: "" });
    this.setData({ addressDj: 0 });
  },
  area:function(e){
    let addressDj = this.data.addressDj;//区域当前级别  第三级赋值
    let index = e.currentTarget.id;
    let rows = this.data.address;
    var info = this.data.info;
    let addressStr = this.data.addressStr;
    addressStr = addressStr + " "+rows[index].areaname;
    this.setData({ addressStr: addressStr });

    if (addressDj < 2){
      this.address(rows[index].areaid);
      addressDj = Number(addressDj)+1;
      this.setData({addressDj});
    }else{
      info.area_areaid = rows[index].areaid;
      info.areaName = addressStr;
      this.setData({ info: info, areaFlag: 0});
    }
  },
  //选择地址
  map: function () {
    let that = this;
    var info = this.data.info;
    //微信内置地图选择地址
    wx.chooseLocation({
      success: function (res) {
        console.log(res);
        info.address = res.address;//地址
        info.longitude = res.longitude;   //经度
        info.latitude = res.latitude;   //纬度
        that.setData({ info: info });
      },
    })
  },
  //商家类型
  types: function () {
    var that = this;
    var params = new Object();
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/business/getBusinessType",
      dataType: "json",
      method: "GET",
      data: params,
      success: function (res) {
        res = res.data;
        console.log("类型：" + JSON.stringify(res));
        if (res.result == 0) {
          let rows = res.data;
          that.setData({ types: rows })
        }
      }
    })
  },
  typeFlag:function(){
    this.setData({ typeFlag:1})
  },
  getType: function (e) {
    let index = e.currentTarget.id;
    let rows = this.data.types;
    var info = this.data.info;
    info.business_type = rows[index].id;
    info.businessTypeName = rows[index].name;
    this.setData({ info: info });
    this.setData({ typeFlag: 0})
  },

  //获取openid
  goPay: function () {
    let info = this.data.info;
    let total = info.price;//合计为0，跳过在线支付
    if (total > 0) {
      var that = this;
      wx.login({
        success: function (res) {
          wx.showLoading({ title: '请稍等...', })
          wx.request({
            header: { "content-Type": "application/x-www-form-urlencoded" },
            url: httpsUrl + "/wechat/getOpenId",
            dataType: "json",
            method: "POST",
            data: { "code": res.code, "agentCode": globalData.agentCode },
            success: function (res) {
              wx.hideLoading();
              res = res.data;
              console.log("获取openid返回:" + JSON.stringify(res));
              if (res.result == 0) {
                let data = JSON.parse(res.data);
                console.log(data.openid);
                that.setData({ openid: data.openid })
                that.pay();
              } else {
                console.log("获取openid失败：" + res.msg);
              }
            }
          })
        }
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '申请提交成功了，请等待审核结果通知哦！',
        success: function (res) {
          if (res.confirm) {
            wx.navigateBack({ delta: 1 })
          } else if (res.cancel) {
            wx.navigateBack({ delta: 1 })
          }
        }
      })
    }
  },
  //支付
  pay: function () {
    let that = this;
    let params = new Object();
    params.orderNo = this.data.orderNo;
    params.openid = this.data.openid;
    console.log(JSON.stringify(params));
    commonUtil.showLoading("去支付...");
    let openId = wx.getStorageSync("openidKey");
    wx.request({
      header: { "openId": openId, "content-Type": "application/x-www-form-urlencoded" },
      url: httpsUrl + "/order/payParam",//统一下单返回支付参数
      dataType: "json",
      method: "POST",
      data: params,
      success: function (res) {
        commonUtil.hideLoading();
        console.log("统一下单返回" + JSON.stringify(res));
        res = res.data;
        if (res.result == 0) {
          var data = res.data;
          //调起支付
          wx.requestPayment(
            {
              'timeStamp': data.timeStamp,
              'nonceStr': data.nonceStr,
              'package': data.package,
              'signType': 'MD5',
              'paySign': data.paySign,
              'success': function (res) {
                console.log("支付调起成功");
                wx.showModal({
                  title: '提示',
                  content: '申请提交成功啦，请等待审核结果通知哦！',
                  success: function (res) {
                    if (res.confirm) {
                      wx.navigateBack({ delta: 1 })
                    } else if (res.cancel) {
                      wx.navigateBack({ delta: 1 })
                    }
                  }
                })
              },
              'fail': function (res) {
                console.log("用户取消支付");
                // wx.switchTab({
                //   url: '../../order/orderList/orderList',
                // })
              },
              'complete': function (res) { }
            })
        } else {
          commonUtil.showModal("支付失败：" + res.msg);
        }
      }
    })
  },

  paySuccess: function () {
    wx.navigateTo({
      url: '../../order/paySuccess/paySuccess',
    })
  },

  onLoad: function (options) {
    this.loadData();
  },

  addImg: function (e) {
    let id = e.currentTarget.id;
    var that = this;
    let openId = wx.getStorageSync("openidKey");
    wx.chooseImage({
      count: 1,  //最多可以选择的图片总数
      sizeType: ['compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        //console.log(JSON.stringify(res));
        var tempFilePaths = res.tempFilePaths;
        let info = that.data.info;
        wx.showToast({
          title: '正在上传...',
          icon: 'loading',
          mask: true,
          duration: 5000
        })
        var uploadImgCount = 0;
        for (var i = 0, h = tempFilePaths.length; i < h; i++) {
          console.log("tempFilePaths[i]:" + tempFilePaths[i]);
          wx.uploadFile({
            header: { "openId": openId, "Content-Type": "multipart/form-data" },
            url: httpsUrl + '/upload/uploadFile',
            filePath: tempFilePaths[i],
            name: 'file',
            formData: {},
            success: function (res) {
              uploadImgCount++;
              let data = res.data;
              console.log("res:" + JSON.stringify(res));
              data = JSON.parse(data);
              // console.log(JSON.stringify(data));
              if (data.result == 0) {
                var imgUrl = data.data.url;
                console.log("imgUrl: " + imgUrl);
                if (id == 0) {
                  info.license = imgUrl;
                }else if (id == 1) {
                  info.img1 = imgUrl;
                } else if (id == 2) {
                  info.img2 = imgUrl;
                } else if (id == 3) {
                  info.img3 = imgUrl;
                } else if (id == 4) {
                  info.logo = imgUrl;
                }
                that.setData({ info: info })
                console.log(JSON.stringify(info));
              } else {
                commonUtil.showModal(data.msg);
              }
              if (uploadImgCount == tempFilePaths.length) {
                wx.hideToast();//如果是最后一张,则隐藏等待中
              }
            },
            fail: function (res) {
              wx.hideToast();
              commonUtil.showModal("上传失败，请重试！");
            }
          });
        }
      }
    });
  },

  name: function (e) {
    let info = this.data.info;
    info.name = e.detail.value;
    this.setData({ info: info})
  },
  contact: function (e) {
    let info = this.data.info;
    info.contact = e.detail.value;
    this.setData({ info: info })
  },
  phone: function (e) {
    let info = this.data.info;
    info.phone = e.detail.value;
    this.setData({ info: info })
  },
  consume: function (e) {
    let info = this.data.info;
    info.consume = e.detail.value;
    this.setData({ info: info })
  },
  shopHourStart: function (e) {
    let info = this.data.info;
    info.shop_hour_start = e.detail.value;
    this.setData({ info: info })
  },
  shopHourEnd: function (e) {
    let info = this.data.info;
    info.shop_hour_end = e.detail.value;
    this.setData({ info: info })
  },
  userName: function (e) {
    let info = this.data.info;
    info.user_name = e.detail.value;
    this.setData({ info: info })
  },
  password: function (e) {
    let info = this.data.info;
    info.password = e.detail.value;
    this.setData({ info: info })
  },
  password2: function (e) {
    let info = this.data.info;
    info.password2 = e.detail.value;
    this.setData({ info: info })
  },
})